<?php


namespace app\operater\controller;


use app\operater\model\Order;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Controller;
use think\Db;

class Operation extends Allow
{
    public function index()
    {
        $op_operation_id = session("op_operation_id");
        if($op_operation_id == 1){
            $data = db("operation")->order("id desc")->paginate(15);
        }else{
            $data = db("operation")->where('id',$op_operation_id)->paginate(1);
        }
        $page = $data->render();
        $data = $data->toArray();
        return view("index",['data' => $data,'page' => $page,'op_id' => $op_operation_id]);
    }
    public function add()
    {
        return view("add");
    }
    public function edit()
    {
        $id = input("id");
        $data = db("operation")->find($id);
        return view("edit",['data' => $data]);
    }
    public function executeData()
    {
        $param = request()->param();
        /*dump($param['account']);die;*/
        $data = [
            'account' => $param['account'],
            'password' => empty($param['password']) ? null : sha1(md5($param['password'])),
            'nickname' => $param['nickname'],
            'ctime' => date("Y-m-d H:i:s",time()),
        ];
        if(empty($param['id'])) {
            $operation = db("operation")->where('account',$data['account'])->find();
            if(!empty($operation)) errorMsg("该账号已经存在");
//            $data[''] =
            $id = db("operation")->insertGetId($data);
            $code = sprintf("%07s",$id);
            $res = db("operation")->where("id",$id)->update(['code' => $code]);
        }else{
//            $operation = db("operation")->where('id',$data['id'])->find();
            if(empty($data['password'])) unset($data['password']);
            $res = db("operation")->where("id",$param['id'])->update($data);
        }
        if($res) return successMsg("成功");
        return errorMsg("失败");
    }
    public function delete()
    {
        $id = input("id");
        $res = db("operation")->where("id",$id)->delete();
        if($res) return successMsg("成功");
        return errorMsg("失败");
    }
    public function editStatus()
    {
        $id = input("id");
        $data = db("operation")->where('id',$id)->find();
        $state = $data['state'] == 0 ? 1 : 0;
        db("operation")->where('id',$id)->update(['state' => $state]);
    }
    public function order()
    {
        $id = (int)input("id") ?? '';
        $user_id = (int)input("user_id") ?? '';
        $op_user_id = 0;
        if(!empty($user_id)){
            $op_user_id = $user_id;
        }
        if(!empty($id)){
            $op_user_id = db("oprelationuser")->where('o_id' ,$id)->column('u_id');
        }
        $order = Db::table("xing_order")->where('user_id','in',$op_user_id)->order('ctime desc')->paginate(50);
        $page = $order->render();
        $order = $order->toarray();
        return view("order",['order' => $order,'page' => $page]);
    }
    public function download()
    {
        $id = input("id");
        $download = db("download")->where('id',$id)->find();
        $data = Db::table("xing_order")->where('order_id','in',$download['order_id'])->select();
        foreach($data as $k=>$v){
            $data[$k]['pay_status'] = Order::payStatus($v['pay_status']);
            $data[$k]['ship_status'] = Order::shipStatus($v['ship_status']);
            $data[$k]['status'] = Order::status($v['status']);
            $data[$k]['tax_type'] = Order::taxType($v['tax_type']);
            $data[$k]['order_type'] = $v['order_type']==1 ? '普通订单':'拼团订单';
            $data[$k]['confirm'] = $v['confirm']==1 ? '未确认收货':'已确认收货';
        }
        $this->my_import($data);
    }
    public function orderDownload(){
        $arr = input('arr');
        array_shift($arr);
        $str = implode(",",$arr);
        $download_id = db("download")->insertGetId(['order_id' => $str]);
        return $download_id;
    }

    public function my_import($data = [])
    {
//        new Spreadsheet()
        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        //设置宽度为true,不然太窄了
        $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        //获取数据库的数据。
        $List = $data;
        $objSheet->setTitle('我的订单');  //设置当前sheet的标题
        //设置第一栏的标题
        $objSheet->setCellValue('A1', '订单号')
            ->setCellValue('B1', '商品总价')
            ->setCellValue('C1', '已支付的金额')
            ->setCellValue('D1', '订单实际销售总额')
            ->setCellValue('E1', '支付状态')
            ->setCellValue('F1', '发货状态')
            ->setCellValue('G1', '订单状态')
            ->setCellValue('H1', '订单类型')
            ->setCellValue('I1', '支付时间')
            ->setCellValue('J1', '配送方式名称')
            ->setCellValue('K1', '配送费用')
            ->setCellValue('L1', '售后状态')
            ->setCellValue('M1', '确认收货时间')
            ->setCellValue('N1', '收货详细地址')
            ->setCellValue('O1', '收货人姓名')
            ->setCellValue('P1', '收货电话')
            ->setCellValue('Q1', '商品总重量')
            ->setCellValue('R1', '税号')
            ->setCellValue('S1', '发票抬头')
            ->setCellValue('T1', '使用积分')
            ->setCellValue('U1', '积分抵扣金额')
            ->setCellValue('V1', '订单优惠金额')
            ->setCellValue('W1', '商品优惠金额')
            ->setCellValue('X1', '优惠券优惠额度')
            ->setCellValue('Y1', '买家备注')
            ->setCellValue('Z1', '卖家备注')
            ->setCellValue('AA1', '创建时间');
        foreach ($List as $k => $val) {
//            dump($val);
            $k = $k + 2;
            $objSheet->setCellValue('A' . $k, $val['order_id'])
                ->setCellValue('B' . $k, $val['goods_amount'])
                ->setCellValue('C' . $k, $val['payed'])
                ->setCellValue('D' . $k, $val['order_amount'])
                ->setCellValue('E' . $k, $val['pay_status'])
                ->setCellValue('F' . $k, $val['ship_status'])
                ->setCellValue('G' . $k, $val['status'])
                ->setCellValue('H' . $k, $val['order_type'])
                ->setCellValue('I' . $k, empty($val['payment_time']) ? '':date("Y-m-d H:i:s",$val['payment_time']))
                ->setCellValue('J' . $k, $val['logistics_name'])
                ->setCellValue('K' . $k, $val['cost_freight'])
                ->setCellValue('L' . $k, $val['confirm'])
                ->setCellValue('M' . $k, empty($val['confirm_time']) ? '':date("Y-m-d H:i:s",$val['confirm_time']))
                ->setCellValue('N' . $k, $val['ship_address'])
                ->setCellValue('O' . $k, $val['ship_name'])
                ->setCellValue('P' . $k, $val['ship_mobile'])
                ->setCellValue('Q' . $k, $val['weight'])
                ->setCellValue('R' . $k, $val['tax_code'])
                ->setCellValue('S' . $k, $val['tax_title'])
                ->setCellValue('T' . $k, $val['point'])
                ->setCellValue('U' . $k, $val['point_money'])
                ->setCellValue('V' . $k, $val['order_pmt'])
                ->setCellValue('W' . $k, $val['goods_pmt'])
                ->setCellValue('X' . $k, $val['coupon_pmt'])
                ->setCellValue('Y' . $k, $val['memo'])
                ->setCellValue('Z' . $k, $val['mark'])
                ->setCellValue('AA' . $k, empty($val['ctime']) ? '':date('Y-m-d H:i:s',$val['ctime']));
        }
        $this->downloadExcel($newExcel, '我的订单', 'Xls');
    }
    //公共文件，用来传入xls并下载
    public function downloadExcel($newExcel, $filename, $format)
    {
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);
//        IOFactory::class
//        IOFactory::class
        $objWriter->save('php://output');

        //通过php保存在本地的时候需要用到
        //$objWriter->save($dir.'/demo.xlsx');

        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
//         If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        exit;
    }

}